package com.banciyuan.bcywebview.utils.sns;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.TextUtils;

import com.banciyuan.bcywebview.R;
import com.banciyuan.bcywebview.base.factory.TimelineFactory;
import com.banciyuan.bcywebview.biz.share.JumpDialog;
import com.banciyuan.bcywebview.utils.string.StringUtil;
import com.sina.weibo.sdk.api.ImageObject;
import com.sina.weibo.sdk.api.TextObject;
import com.sina.weibo.sdk.api.WeiboMultiMessage;
import com.sina.weibo.sdk.share.WbShareHandler;
import com.tencent.connect.share.QQShare;
import com.tencent.connect.share.QzoneShare;
import com.tencent.mm.sdk.modelmsg.SendMessageToWX;
import com.tencent.mm.sdk.modelmsg.WXMediaMessage;
import com.tencent.mm.sdk.modelmsg.WXWebpageObject;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;

import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import de.greenrobot.daoexample.model.Timeline;


/**
 * 社会化分享工具类.
 *
 * @author hfxt2008
 *         具体参见友盟社会化分享的文档
 *         其中新浪微博分享是接入了新浪微博的sdk，请参见新浪微博sdk的文档
 */
public class SnsUtil {

    private static JumpDialog jumpDialog;

    public static void share2QQ(Context mContext, Map<String, String> map, Tencent mTencent) {
        Bundle params = new Bundle();
        params.putInt(QQShare.SHARE_TO_QQ_KEY_TYPE, QQShare.SHARE_TO_QQ_TYPE_DEFAULT);
        params.putString(QQShare.SHARE_TO_QQ_TITLE, map.get("title"));
        params.putString(QQShare.SHARE_TO_QQ_SUMMARY, map.get("content"));
        params.putString(QQShare.SHARE_TO_QQ_TARGET_URL, map.get("url"));
        if (!TextUtils.isEmpty(map.get("imagePath")))
            params.putString(QQShare.SHARE_TO_QQ_IMAGE_URL, map.get("imagePath"));
        mTencent.shareToQQ((Activity) mContext, params, new IUiListener() {
            @Override
            public void onComplete(Object o) {
            }

            @Override
            public void onError(UiError uiError) {
            }

            @Override
            public void onCancel() {
            }
        });
    }

    public static void shareToQQZone(Context mContext, Map<String, String> map, Tencent mTencent) {
        Bundle params = new Bundle();
        params.putInt(QzoneShare.SHARE_TO_QZONE_KEY_TYPE, QzoneShare.SHARE_TO_QZONE_TYPE_IMAGE_TEXT);
        params.putString(QzoneShare.SHARE_TO_QQ_TITLE, map.get("title"));
        params.putString(QzoneShare.SHARE_TO_QQ_SUMMARY, map.get("content"));
        params.putString(QzoneShare.SHARE_TO_QQ_TARGET_URL, map.get("url"));
        ArrayList<String> imgUrls = new ArrayList<>();
        if (!TextUtils.isEmpty(map.get("imagePath"))) {
            imgUrls.add(map.get("imagePath"));
        }
        params.putStringArrayList(QzoneShare.SHARE_TO_QQ_IMAGE_URL, imgUrls);
        mTencent.shareToQzone((Activity) mContext, params, new IUiListener() {
            @Override
            public void onComplete(Object o) {
            }

            @Override
            public void onError(UiError uiError) {
            }

            @Override
            public void onCancel() {
            }
        });
    }

    public static void share2Weixin(final Context mContext, final Map<String, String> map, final IWXAPI mWxApi) {
        showJumpingDialog(mContext);
        final String url = map.get("imagePath");
        new AsyncTask<Void, Void, Bitmap>() {
            @Override
            protected Bitmap doInBackground(Void... params) {
                return getBitmap(url);
            }

            @Override
            protected void onPostExecute(Bitmap bmp) {
                if (null == bmp) {
                    bmp = BitmapFactory.decodeResource(mContext.getResources(), R.drawable.ic_launcher2);
                }
                share2BaseWeixinWithPic(bmp, map, mContext, mWxApi, SendMessageToWX.Req.WXSceneSession);
            }
        }.execute();
    }

    public static void share2Circle(final Context mContext, final Map<String, String> map, final IWXAPI mWxApi) {
        showJumpingDialog(mContext);
        final String url = map.get("imagePath");
        new AsyncTask<Void, Void, Bitmap>() {
            @Override
            protected Bitmap doInBackground(Void... params) {
                return getBitmap(url);
            }

            @Override
            protected void onPostExecute(Bitmap bmp) {
                if (null == bmp) {
                    bmp = BitmapFactory.decodeResource(mContext.getResources(), R.drawable.ic_launcher2);
                }
                share2BaseWeixinWithPic(bmp, map, mContext, mWxApi, SendMessageToWX.Req.WXSceneTimeline);
            }
        }.execute();
    }

    private static void share2BaseWeixinWithPic(Bitmap bmp, Map<String, String> map, Context mContext, IWXAPI mWxApi, int weixinsession) {
        WXMediaMessage.IMediaObject mediaObj;
        WXWebpageObject webpage = new WXWebpageObject();
        webpage.webpageUrl = map.get("url");
        mediaObj = webpage;
        WXMediaMessage msg = new WXMediaMessage(mediaObj);
        msg.title = map.get("title");
        msg.description = map.get("content");
        byte[] reBmp = Util.bmpToByteArray(bmp, true);
        if (reBmp != null) {
            msg.thumbData = Util.bmpToByteArray(bmp, true);
        } else {
            msg.thumbData = Util.bmpToByteArray(BitmapFactory.decodeResource(mContext.getResources(), R.drawable.ic_launcher2), true);
        }
        SendMessageToWX.Req req = new SendMessageToWX.Req();
        req.transaction = String.valueOf(System.currentTimeMillis());
        req.scene = weixinsession;
        req.message = msg;
        dismissJumpingDialog(mContext);
        mWxApi.sendReq(req);
        bmp.recycle();
    }

    public static void share2Weibo(final WbShareHandler shareHandler, final Map<String, String> map) {
        final String url = map.get("imagePath");
        new AsyncTask<Void, Void, Bitmap>() {
            @Override
            protected Bitmap doInBackground(Void... params) {
                return getBitmap(url);
            }

            @Override
            protected void onPostExecute(Bitmap bmp) {
                if (null == bmp) {
                    share2WeiboWithOutPic(shareHandler, map);
                } else {
                    share2WeiboWithPic(bmp, map, shareHandler);
                }
            }
        }.execute();
    }

    private static void share2WeiboWithPic(Bitmap bmp, Map<String, String> map, WbShareHandler shareHandler) {
        WeiboMultiMessage weiboMessage = new WeiboMultiMessage();
        TextObject textObject = new TextObject();
        textObject.text = map.get("content");
        weiboMessage.textObject = textObject;
        ImageObject imageObject = new ImageObject();
        imageObject.setImageObject(Util.bmpToSmall(bmp, 2 * 1000 * 1000));
        imageObject.setThumbImage(Util.bmpToSmall(bmp, 32 * 1000));
        weiboMessage.imageObject = imageObject;
        shareHandler.shareMessage(weiboMessage, false);
        bmp.recycle();
    }

    public static void share2WeiboWithOutPic(final WbShareHandler shareHandler, final Map<String, String> map) {
        WeiboMultiMessage weiboMessage = new WeiboMultiMessage();// 初始化微博的分享消息
        TextObject textObject = new TextObject();
        if (!TextUtils.isEmpty(map.get("content"))) {
            textObject.text = map.get("content");
            weiboMessage.textObject = textObject;
        }
        shareHandler.shareMessage(weiboMessage, false);
    }

    private static Bitmap getBitmap(String url) {
        if (TextUtils.isEmpty(url)) return null;
        Bitmap bmp = null;
        try {
            bmp = BitmapFactory.decodeStream(new URL(url).openStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
        return bmp;
    }

    public static void showJumpingDialog(Context mContext) {
        try {
            if (!((Activity) mContext).isFinishing()) {
                JumpDialog.Builder builder = new JumpDialog.Builder(mContext);
                jumpDialog = builder.create();
                jumpDialog.show();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void dismissJumpingDialog(Context mContext) {
        try {
            if (!((Activity) mContext).isFinishing() && null != jumpDialog && jumpDialog.isShowing()) {
                jumpDialog.dismiss();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static String getTitle(Timeline timeline, Context mContext) {
        if (!TextUtils.isEmpty(timeline.getTitle())) {
            if (timeline.getTimelineType() == TimelineFactory.TIMELINE_TYPE_GOODS) {
                return String.format(mContext.getString(R.string.share_goods_title), timeline.getTitle());
            } else {
                return timeline.getTitle() + " -- 半次元";
            }
        } else {
            return "来自半次元";
        }
    }

    private static String getContent(Timeline timeline, String url, Context mContext) {
        int type = timeline.getTimelineType();
        switch (type) {
            case TimelineFactory.TIMELINE_TYPE_COSER:
                return String.format(mContext.getString(R.string.share_cos), timeline.getOUName(), url);
            case TimelineFactory.TIMELINE_TYPE_ILLUST:
                return String.format(mContext.getString(R.string.share_draw), timeline.getOUName(), url);
            case TimelineFactory.TIMELINE_TYPE_DAILY:
                if (!StringUtil.notNullEqual(timeline.getType(), "svideo")) {
                    return String.format(mContext.getString(R.string.share_daily), timeline.getOUName(), url);
                } else {
                    return String.format(mContext.getString(R.string.share_video), timeline.getTitle(), timeline.getOUName(), url);
                }
            case TimelineFactory.TIMELINE_TYPE_GROUP:
                return String.format(mContext.getString(R.string.share_group_post), timeline.getOUName(), url);
            case TimelineFactory.TIMELINE_TYPE_WRITER:
                return String.format(mContext.getString(R.string.share_write), timeline.getOUName(), url);
            case TimelineFactory.TIMELINE_TYPE_POLAROID:
                return String.format(mContext.getString(R.string.share_polaroid), url);
            case TimelineFactory.TIMELINE_TYPE_GOODS:
                return String.format(mContext.getString(R.string.share_goods), timeline.getTitle(), timeline.getOUName(), url);
            case TimelineFactory.TIMELINE_TYPE_OTHER:
            default:
                return null;
        }
    }

    private static String getUrl(Timeline timeline) {
        int type = timeline.getTimelineType();
        switch (type) {
            case TimelineFactory.TIMELINE_TYPE_COSER:
                return "http://bcy.net/coser/detail/" + timeline.getCp_id() + "/" + timeline.getRp_id();
            case TimelineFactory.TIMELINE_TYPE_ILLUST:
                return "http://bcy.net/illust/detail/" + timeline.getDp_id() + "/" + timeline.getRp_id();
            case TimelineFactory.TIMELINE_TYPE_DAILY:
                return "http://bcy.net/daily/detail/" + timeline.getUd_id();
            case TimelineFactory.TIMELINE_TYPE_GROUP:
                return "http://bcy.net/group/detail/" + timeline.getGid() + "/" + timeline.getPost_id();
            case TimelineFactory.TIMELINE_TYPE_WRITER:
                return "http://bcy.net/novel/detail/" + timeline.getWp_id() + "/" + timeline.getRp_id();
            case TimelineFactory.TIMELINE_TYPE_POLAROID:
                if (null != timeline.getCp_id() && !TextUtils.isEmpty(timeline.getCp_id()))
                    return "http://bcy.net/group/detail/" + timeline.getCp_id() + "/" + timeline.getRp_id();
                else
                    return "http://bcy.net/daily/detail/" + timeline.getRp_id();
            case TimelineFactory.TIMELINE_TYPE_GOODS:
                return "http://bcy.net/zhipin/detail/" + timeline.getZg_id();
            case TimelineFactory.TIMELINE_TYPE_OTHER:
            default:
                return null;
        }
    }

    public static String getImagePath(Timeline timeline) {
        int type = timeline.getTimelineType();
        switch (type) {
            case TimelineFactory.TIMELINE_TYPE_COSER:
            case TimelineFactory.TIMELINE_TYPE_ILLUST:
            case TimelineFactory.TIMELINE_TYPE_WRITER:
            case TimelineFactory.TIMELINE_TYPE_POLAROID:
            case TimelineFactory.TIMELINE_TYPE_GOODS:
                return timeline.getContentAddress();
            case TimelineFactory.TIMELINE_TYPE_DAILY:
            case TimelineFactory.TIMELINE_TYPE_GROUP:
                try {
                    List<String> addressList = Arrays.asList(timeline.getContentAddress().split(" "));
                    if (addressList.isEmpty()) return "";
                    return addressList.get(0);
                } catch (Exception e) {
                    return "";
                }
            case TimelineFactory.TIMELINE_TYPE_OTHER:
            default:
                return "";
        }
    }

    public static Map<String, String> parseTimeLine(Timeline timeline, Context mContext) {
        if (timeline == null) return null;
        String url = getUrl(timeline);
        String content = getContent(timeline, url, mContext);
        String imagePath = getImagePath(timeline);
        String title = getTitle(timeline, mContext);
        Map<String, String> map = new HashMap<String, String>();
        map.put("url", url);
        map.put("content", content);
        map.put("imagePath", imagePath);
        map.put("title", title);
        return map;
    }

    public static Map<String, String> parseTimeLine(Context mContext, String url, String imagePath, String content, String title) {
        Map<String, String> map = new HashMap<>();
        map.put("url", url);
        map.put("content", content);
        map.put("imagePath", imagePath);
        map.put("title", title);
        return map;
    }
}
